package com.ldfile.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class UrlFilter implements Filter {

    @Autowired
    FileServiceInfoConfiguration fileServiceInfoConfiguration;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        String path = httpRequest.getRequestURI().replaceFirst(httpRequest.getContextPath(), "");

        if (path.startsWith(fileServiceInfoConfiguration.getPathYml())
                && !StringUtils.isEmpty(httpRequest.getParameter("width"))
                && !StringUtils.isEmpty(httpRequest.getParameter("height"))) {
            String forwardPath = String.format("/api/getFileTumb%s", path.replace(fileServiceInfoConfiguration.getPathYml(), ""));
            httpRequest.getRequestDispatcher(forwardPath).forward(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
